import java.util.Comparator;
import java.util.HashMap;
import java.util.PriorityQueue;

/**
 * @program: LeetCode
 * @description: LeetCode : 剑指 Offer II 060. 出现频率最高的 k 个数字
 * @author: WXY
 * @create: 2023-01-06 09:37
 * @Version 1.0
 **/
public class offer_twenty2_topKFrequent {
    public static int[] topKFrequent(int[] nums, int k) {
        int[] ans = new int[k];
        HashMap<Integer, Integer> map = new HashMap<>();
        PriorityQueue<int[]> heap = new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o2[1] - o1[1];
            }
        });
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        for (Integer i : map.keySet()) {
            heap.add(new int[]{i, map.get(i)});
        }
        for (int i = 0; i < k; i++) {
            ans[i] = heap.poll()[0];
        }
        return ans;
    }
}
